import { RbacMenuType } from '@/data/auth/menu';
import { useAdminPermissions } from '@/hooks/auth/usePermissions';
import { list } from '@/services/data';
import { Form, Modal, Transfer } from 'antd';
import React, { useEffect, useState } from 'react';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<RbacMenuType> & {
    targetKeys?: React.Key[];
  };

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<RbacMenuType>;
  correlationType: number;
};

const AddPermModal: React.FC<UpdateFormProps> = (props) => {
  const { adminPermissions }: any = useAdminPermissions();
  const transformedData =
    adminPermissions?.map(({ id, urlPerm, remark }: any) => ({
      name: `${urlPerm} ${remark}`,
      key: id,
    })) || [];

  const initialTargetKeys: React.Key[] | (() => React.Key[]) = [];
  const [form] = Form.useForm<FormValueType>();
  const [targetKeys, setTargetKeys] = useState<React.Key[]>(initialTargetKeys);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      const menuOrBtnId = props.values.id;
      const correlationType = props.correlationType;
      const hasPermList = await list('/system/rbacPermissionMenuBtn', {
        menuOrBtnId,
        correlationType,
      });
      const hasPermIdList = hasPermList?.list?.map((btn: any) => btn.permissionId) || [];

      setTargetKeys(hasPermIdList);
    };
    if (props.updateModalVisible && props.values.id) fetchData();
  }, [props.values, props.updateModalVisible]);

  const handleOk = async () => {
    await props.onSubmit({ targetKeys });
  };

  const handleChange = (targetKeys: React.Key[]) => {
    setTargetKeys(targetKeys);
  };

  const handleSelectChange = (sourceSelectedKeys: React.Key[], targetSelectedKeys: React.Key[]) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  return (
    <Modal
      width={1200}
      style={{
        padding: '32px 40px 48px',
      }}
      title="授权"
      open={props.updateModalVisible}
      onCancel={() => {
        props.onCancel();
      }}
      onOk={handleOk}
      key={`menu-add-perm-${props.values?.id || Math.random()}`}
    >
      <Form form={form} initialValues={props.values}>
        <Transfer
          listStyle={{
            width: 500,
            height: 600,
          }}
          dataSource={transformedData}
          titles={['未得到权限', '已拥有权限']}
          targetKeys={targetKeys}
          selectedKeys={selectedKeys}
          onChange={handleChange}
          onSelectChange={handleSelectChange}
          render={({ name }) => `${name}`}
        />
      </Form>
    </Modal>
  );
};

export default AddPermModal;
